<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\service;

use think\Exception;

/**
 * 微信模版消息管理
 * Class WxMessage
 * @package app\api\service
 */
class WxMessage {

    private $__sendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?" .
    "access_token=%s";
    private $__touser;
    //不让子类控制颜色
    private $__color = 'black';

    protected $_tplID;
    protected $_page;
    protected $_formID;
    protected $_data;
    protected $_emphasisKeyWord;
    
    function __construct()
    {
        $accessToken = new AccessToken();
        $token = $accessToken->get();
        $this->__sendUrl = sprintf($this->__sendUrl, $token);
    }

    // 开发工具中拉起的微信支付prepay_id是无效的，需要在真机上拉起支付
    protected function _sendMessage($openID)
    {

        $data = [
            'touser' => $openID,
            'template_id' => $this->_tplID,
            'page' => $this->_page,
            'form_id' => $this->_formID,
            'data' => $this->_data,
            //'color' => $this->__color,
            'emphasis_keyword' => $this->_emphasisKeyWord
        ];
        $result = curl_post($this->__sendUrl, $data);
        $result = json_decode($result, true);
        if ($result['errcode'] == 0) {
            return true;
        } else {
            throw new Exception('模板消息发送失败,  ' . $result['errmsg']);
        }
    }
}